<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script>
window.p = {
	consoleFn: parent.consoleFn,
	isTab:false,
	createrId: "${SESSION_USER.user.id}",
	className: "${className}" || null,
	modleName: "${modleName}" || null,
	queryForm: "#queryForm",
	dataGrid : "#dataGrid",
	menuId: 	"${param.menuId}",
	/**
	*自定义弹出框
	*/
    dialog: null,
    /**
    *刷新父列表
    */
    refreshParent: function(msg){
    	p.tip({msg:  msg || '操作成功！'}); 
    	if(p.dialog!=null)  p.dialog.dialog("close");
    	var isTreeGrid = this.isTreeGrid || false;
    	if(isTreeGrid){
	    	if(p.dataGrid) $(p.dataGrid).treegrid("reload");
    	}else{
    		if(p.dataGrid) $(p.dataGrid).datagrid("reload");
    	}
    	p.dataGrid.datagrid('clearSelections');//清除所有选择的行
	},
	/**
	*表格查询
	*/
	gridQuery:function(param){
		var formParam = $(this.queryForm).serializeObject() ;
		formParam = $.extend({},formParam, param || {} );
		var queryParams = null; 
		if(this.dataGrid){
			var isTreeGrid = this.isTreeGrid || false;
			if(isTreeGrid){
				queryParams = this.dataGrid.treegrid('options').queryParams || {};
				queryParams = $.extend(queryParams,formParam);
				this.dataGrid.treegrid('load', queryParams );
			}else{
				if(this.dataGrid.datagrid){
					queryParams = this.dataGrid.datagrid('options').queryParams || {} ;
					queryParams = $.extend(queryParams,formParam);
					this.dataGrid.datagrid('load', queryParams );
				}
				return false;
			}
		}
	},
	/**
	*生成tabId=menuId-longtime
	*/
	_newTabId: function(){
		var tabId = [];
		tabId.push(this.menuId);
		tabId.push(new Date().getTime());
		tabId = tabId.join("-");
		return tabId;
	},
	/**
	*新增
	*/
	gridAdd:function(param){
		var _this = this;
		var _p = {
			title : "${modleName}新增", width : 400, height : 300, href : p.gridAddUrl,
			data: param.data || null,
			buttons : [ p.buttons.submit, p.buttons.close ]
		};
		_p = $.extend(_p,param || {});
		if(_this.isTab==true || _p.isTab==true){
			var tabId = _this._newTabId();
			_this.consoleFn.addTab(_p.title,tabId,_p.href,'icon-add');
		}else{
			var win = p.dialog = $("<div/>").dialog("openWin", _p);
			if(_p.autoMax){
				win.panel('maximize');
			}
		}
	},
	/**
	*编辑
	*/
	gridModify:function(param){
		var _this = this;
		var rows = p.dataGrid.datagrid('getSelections'), len = rows.length || 0 ;
		if(len<=0){
			p.tip({ msg : '请选择一条记录进行操作！' }); return;
		} 

		/*控制只能自己修改自己的数据*/
		if(param.onlyMySelf && rows[0].createrId &&  p.createrId!=rows[0].createrId){
			p.tip({ msg : '您无权操作此记录！' }); return;
		}
		
		if(param.onOpenBefore){
			var flag = param.onOpenBefore(rows[0]);
			if(flag==false) return ;
		}
		
		var _p = {
				title : "${modleName}编辑", width : 400, height : 300, href : p.gridModifyUrl,
				data : rows[0],
				buttons : [ p.buttons.submit, p.buttons.close ]
		};
		_p = $.extend(_p,param || {});
		if(_this.isTab==true || _p.isTab==true){
			var tabId = _this._newTabId();
			_this.consoleFn.addTab(_p.title,tabId,_p.href,'icon-edit',_p.data);
		}else{
			var win = p.dialog = $("<div/>").dialog("openWin", _p);
			if(_p.autoMax){
				win.panel('maximize');
			}
		}
	},
	/**
	*/
	gridOpt: function(param){
		var _this = this;
		var rows = p.dataGrid.datagrid('getSelections'), len = rows.length || 0 ;
		if(len<=0){
			p.tip({ msg : '请选择一条记录进行操作！' }); return;
		} 
		var _p = {
				title : "操作", width : 400, height : 300, href : null,autoMax:false,
				data : rows[0],
				buttons : [ p.buttons.close ]
		};
		_p = $.extend(_p,param || {});
		if(_this.isTab==true || _p.isTab==true){
			var tabId = _this._newTabId();
			_this.consoleFn.addTab(_p.title,tabId,_p.href,'tree-file',_p.data);
		}else{
			var win = p.dialog = $("<div/>").dialog("openWin", _p);
			if(_p.autoMax){
				win.panel('maximize');
			}
		}
	},
	
	/**
	*编辑
	*/
	gridView:function(param){
		var _this = this;
		var rows = p.dataGrid.datagrid('getSelections'), len = rows.length || 0 ;
		if(len<=0){
			p.tip({ msg : '请选择一条记录进行查看！' }); return;
		} 
		var _p = {
				title : "${modleName}查看", width : 400, height : 300, href : p.gridViewUrl,
				data : rows[0],
				buttons : [p.buttons.close]
		};
		_p = $.extend(_p,param || {});
		if(_this.isTab==true || _p.isTab==true){
			var tabId = _this._newTabId();
			_this.consoleFn.addTab(_p.title,tabId,_p.href,'icon-view',_p.data);
		}else{
			var win = p.dialog = $("<div/>").dialog("openWin", _p);
			if(_p.autoMax){
				win.panel('maximize');
			}
		}
	},
	/**
	*表单确认操作
	*
	*/
	gridConfirm:function(param){
		var rows = p.dataGrid.datagrid('getSelections'), len = rows.length || 0 ;
		if(len<=0){
			p.tip({ msg : '请选择一条记录进行操作！' }); return;
		} 
		var row = rows[0];
		if(param.onOpenBefore){
			var flag = param.onOpenBefore(row);
			if(flag==false) return ;
		}
		
		if(!param.url){
			p.tip({ msg : '未配置Confirm的url参数！' }); return;
		}
		
		var title = param.title || '确认做此操作码？';
		var msg =  param.msg || '操作成功！';
		
		var _p =  $.extend(row, param.data || {});
		$.messager.confirm('确认对话框', title , function(r){if (r){
			$.getJSON(param.url, _p ,function(res){
				if(res.flag){
					p.tip({ msg: msg });  
					p.gridQuery();
				}else{
					p.tip({msg:  res.msg});  
				}
        	 });
		}});
	},
	
	/**常用表单按钮操作*/
	buttons:{
		close:{
			text : "关闭", iconCls : "icon-no", handler : function() {
				p.dialog.dialog('close');
			}
		},
		submit:{
			text : "提交", id:'f_btn_submit', iconCls : "icon-edit", handler : function() {
				$('#f_btn_submit').linkbutton('disable');
				setTimeout(function(){
					$('#f_btn_submit').linkbutton('enable');
				},3000);
				p.dialog.iframeWindow.fn.submitForm();
			}
		},
		clear:{
			text : "清空", iconCls : "icon-reload", handler : function() {
				p.dialog.iframeWindow.fn.clearForm();
			}
		},
		back:{
			text : "驳回", iconCls : "icon-back", handler : function() {
				//p.dialog.iframeWindow.fn.clearForm();
			}
		}
	},
	/**
	*信息tip提示
	*title 标题
	*msg 内容
	*timeout 时间（秒）
	*/
	tip:function(param){
		var tipParam = { title:'我的消息', msg: '^_^这是一条信息提示^_^',timeout:3000, showType:'slide' };
		tipParam = $.extend(tipParam,param || {});
		$.messager.show(tipParam);
	},
	/**
	*表格删除
	*/
	gridDelete:function(param){
		param = param || {} ;
		var rows = param.rows || p.dataGrid.datagrid('getSelections') || [] ;
		var len = rows.length ;
		var msg = param.msg || "您确认删除当前选中记录？";
		var url = param.url || p.gridDeleteUrl;
		if(url=='' || url ==null){
			this.tip({msg: '请正确配置删除地址如：<br/>/console/com.fs.*.EntityName/delete'});
			return;
		}
		if(len<=0){
			this.tip({msg: '选择待删除记录后执行删除！'}); return;
		} 
		
		if(param.onOpenBefore){
			var flag = param.onOpenBefore(rows[0]);
			if(flag==false) return ;
		}
		
		$.messager.confirm('确认对话框', msg, function(r){if (r){
			var data = {};
			if(len==1){ data = {id: rows[0]["id"] || rows[0]["o"]["id"]  || "" };
			}else{ data = {rows: JSON.stringify(rows)}; }
			$.getJSON(url, data, function(result){
				/*清除选中缓存数据*/
				p.dataGrid.datagrid('clearSelections');
				if(result.flag){
					p.gridQuery();
					p.tip({msg: '删除成功！'});  
				} 
			});
		}});
	},
	/**
	选择多条记录
	*/
	getSelections: function(tip){
		var rows = p.dataGrid.datagrid('getSelections'), len = rows.length || 0 ;
		if(len<=0){
			p.tip({ msg : tip || '请选择记录后进行操作！' });
		}
		return rows;
	},
	/**
	选择一条记录
	*/
	getSelection: function(tip){
		var row = null;
		var rows = this.getSelections(tip) ;
		if(rows && rows.length>0){ row = rows[0]; }
		return row;
	},
	gridOpenTab :function(param){
		var title = param.title || '新Tab';
		var tabId = param.tabId || (new Date().getTime());
		var url = param.url || '';
		var iconCls = param.iconCls;
		this.consoleFn.addTab(title,tabId,url,iconCls);
	},
	/**
	*列表默认新增地址
	*/
	gridAddUrl: "/console/${modleName}/preAdd",
	/**
	*列表默认编辑地址
	*/
	gridModifyUrl:"/console/${modleName}/preModify",
	/**
	*表单预览查看
	*/
	gridViewUrl:"/console/${modleName}/view",
	/**
	*列表默认编辑地址
	*/
	gridDeleteUrl: ("${className}" || null)? "/console/${className}/delete" : null ,
	/**
	*列表默认配置地址
	*/
	gridConfigUrl: "/console/${modleName}/config" ,
	/**
	*grid down url
	*/	
	gridDownUrl: "/console/${modleName}/export" ,
	/**
	*grid列表默认参数配置
	*/
	dataGridParam:{
		idField: "id",
		toolbar:"#toolbar",
		fit: true,
		rownumbers: true,
		pagination: true,
		singleSelect: true, 
		url:  ("${className}" || null) ?  "/console/${className}/list" : null ,
		columns: [[
			{"field":"fieldQuery","width":200,"title":"虚位以待A(queryForm表单替换)"},
			{"field":"fieldColumns","width":200,"title":"虚位以待B(columns属性替换)"},
			{"field":"fieldUrl","width":200,"title":"虚位以待C(url属性替换)"}        
		]],
		/*动态追加访问菜单id，实现菜单数据权限控制*/
		onBeforeLoad:function(param){
			if(param){
				if(p.menuId) param.accessMenuId = p.menuId;
				
				if(p.className) param.className = p.className;
			}
		}
	},
	init:function(param){
		window.p = $.extend(this,param || {} );
	},
	openWindowInHidden: function (opts) {
		opts = $.extend({
			url: '',
			method: 'POST',
			target: '',
			queryParams: {}
		}, opts);
		if (!opts.url) return;
		if (!opts.target && 0 >= $('#hideFrameOfOpenWindow').length) {
			$('<iframe id="hideFrameOfOpenWindow" name="hideFrameOfOpenWindow"></iframe>').hide().appendTo(document.body);
		}
		if ((opts.method || '').toUpperCase() === 'GET') {
			var url = opts.url || '', params = $.isPlainObject(opts.queryParams) ? $.param(opts.queryParams, true) : opts.queryParams;
			if (!!params) url += (0 > url.indexOf('?') ? '?' : '&') + params;
			window.open(url, !!opts.target && opts.target || 'hideFrameOfOpenWindow');
		} else {
			var $form = $('#hideFormOfOpenWindow'), val;
			if (0 >= $form.length) {
				$form = $('<form id="hideFormOfOpenWindow" method="post" target="hideFrameOfOpenWindow"></form>');
				$form.hide().appendTo(document.body);
			}
			!!opts.target && $form.attr('target', opts.target);
			$form.empty();
			createHidden('', opts.queryParams);
			$form.attr('action', opts.url);
			$form[0].submit();
			function createHidden(key, val) {
				if (!!key && (val === undefined || val === null)) {
					$('<input type="hidden"/>').attr('name', key).appendTo($form);
				} else if ($.isArray(val)) {
					$.each(val, function () {
						createHidden(key, this);
					});
				} else if ($.isPlainObject(val)) {
					for (var name in val) {
						createHidden((!!key && (key + '.') || '') + name, val[name]);
					}
				} else if (!!key && !$.isFunction(val)) {
					$('<input type="hidden"/>').attr('name', key).val(val).appendTo($form);
				}
			}
		}
	},
	total: function(opt){
		var _this = this;
		var total = {};
		var param = $.extend({fields:null,sumTitle:'total:'},opt || {} );
		if(param.fields){
			var data = _this.dataGrid.datagrid('getData');
			if(data.rows.length<=0){
				return false;
			}
			var temp = null;
			$.each(data.rows ||[], function (i,item) {
				$.each(param.fields, function (f,field) {
					 if(field.total=='sum'){
						 field.count = field.count || 0;
						 temp = item[field.name] || 0;
						 field.count += parseFloat(temp);
					 } 
				});
			});
		}
		var appendRow = {}; appendRow[param.tipName] = param.tip;
		$.each(param.fields, function (j,fItem) {
			appendRow[fItem.name] = fItem.count.toFixed(2);
		});
		_this.dataGrid.datagrid('appendRow',appendRow);
	},
	down: function(opts){
		opts = opts || {};
		var queryParams = {},headers = [];
		var _this = this;
		var grid = opts.grid || this.dataGrid ;
		if(grid){
			var isTreeGrid = this.isTreeGrid || false;
			if(isTreeGrid){
				queryParams = this.dataGrid.treegrid('options').queryParams || {};
				headers = this.dataGrid.treegrid('options').columns;
			}else{
				queryParams = grid.datagrid('options').queryParams || {} ;
				headers = grid.datagrid('options').columns;
			}
		}
		var param = {headers: headers, filename: opts.filename || 'fileDown',local: opts.local || false };
		
		if(param.local){
			param.data = grid.datagrid('getData').rows;
		}
		this.openWindowInHidden({
			  url: opts.url || _this.gridDownUrl,
			  queryParams: $.extend(queryParams,{exportJson: JSON.stringify(param)})
		 });
	},
	/*
	*窗口自适应
	*/
	gridResize: function(){
		$('body .easyui-layout').layout('resize', { width:'100%' });
    	$('#toolbar').css({width:'100%'});
	},
	btnOneClick:function($btn){
		$btn.linkbutton('disable');
		setTimeout(function(){
			$btn.linkbutton('enable');
		},200);
	},
	/*
	*表格字段tooltip
	**/
	tooltip:function(field){
		var fields = [];
		var _field = field || '';
		if(_field instanceof Array){
			fields = _field;
		}else{
			fields.push(_field);
		}
		$.each(fields, function (i,item) {
			$("td[field="+ item +"] div").tooltip({ content: function(){ return $(this).text(); } });
		});
	}
};

$(function(){
	//判断当前浏览器是否支持JSON对象，如果不支持，则引入json2.js文件
	if(typeof JSON == 'undefined'){
		$('head').append('<script type="text/javascript" src="/plug-in/other/json2.js">');
	}
	//1.回车键绑定
	$(document).keypress(function(e) {  
		if(e.which == 13) p.gridQuery(); 
	}); 
	
	//浏览器窗口大小变化后，表格宽度自适应
    $(window).resize(function(){
    	p.gridResize();
    	
    });
	
	//2.当前菜单所对应的按钮动作权限
	var menuMotions = '${PARAM_MENU_MOTIONS}' || '[]';
	menuMotions = JSON.parse(menuMotions);
	var btns = []
	$.each(menuMotions,function(index,btn){
		btns.push('<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="'+ btn.motionIcon +'" plain="true" motion_code="'+ btn.motionCode +'">'+ btn.motionName +'</a>');
	});
	btns = btns.join('');
	$("#toolbar").append(btns);
	$.parser.parse("#toolbar");
});

</script>